<template>
  <div class="comment-management">
    <div class="header">
      <h1>评论管理</h1>
      <div class="filter-actions">
        <a-radio-group v-model:value="filterStatus" @change="handleFilterChange">
          <a-radio-button :value="null">全部</a-radio-button>
          <a-radio-button :value="1">已发布</a-radio-button>
          <a-radio-button :value="0">待审核</a-radio-button>
          <a-radio-button :value="-1">已拒绝</a-radio-button>
        </a-radio-group>
        
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索评论内容"
          style="width: 250px; margin-left: 16px"
          @search="handleSearch"
        />
      </div>
    </div>
    
    <a-table
      :columns="columns"
      :data-source="commentStore.commentList"
      :loading="commentStore.loading"
      :pagination="{
        total: commentStore.total,
        current: current,
        pageSize: pageSize,
        onChange: handlePageChange,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50'],
        onShowSizeChange: handleSizeChange
      }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'content'">
          <div class="comment-content">
            <div v-html="formatContent(record.content)"></div>
            <div v-if="record.parentId > 0" class="reply-info">
              回复 <a-tag color="blue">@{{ record.replyToUsername }}</a-tag>
            </div>
          </div>
        </template>
        
        <template v-if="column.key === 'article'">
          <a @click="viewArticle(record.articleId)">{{ getArticleTitle(record.articleId) }}</a>
        </template>
        
        <template v-if="column.key === 'user'">
          <div class="user-info">
            <a-avatar :src="getStaticUrl(record.avatar)" size="small" />
            <span class="username">{{ record.username }}</span>
          </div>
        </template>
        
        <template v-if="column.key === 'createTime'">
          {{ formatDate(record.createTime) }}
        </template>
        
        <template v-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button 
              v-if="record.status !== 1" 
              type="primary" 
              size="small"
              @click="handleApprove(record)"
            >
              通过
            </a-button>
            <a-button 
              v-if="record.status !== -1" 
              danger 
              size="small"
              @click="handleReject(record)"
            >
              拒绝
            </a-button>
            <a-button 
              type="dashed" 
              size="small"
              @click="handleReply(record)"
            >
              回复
            </a-button>
            <a-popconfirm
              title="确定要删除这条评论吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record)"
            >
              <a-button danger size="small">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
    
    <!-- 回复评论的模态框 -->
    <a-modal
      v-model:visible="replyModalVisible"
      title="回复评论"
      @ok="submitReply"
      :confirmLoading="submitting"
    >
      <div class="original-comment" v-if="currentComment">
        <p><strong>{{ currentComment.username }}:</strong></p>
        <div v-html="formatContent(currentComment.content)"></div>
      </div>
      
      <a-form layout="vertical" style="margin-top: 16px">
        <a-form-item label="回复内容">
          <a-textarea
            v-model:value="replyContent"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useCommentStore } from '@/stores/comment';
import { useArticleStore } from '@/stores/article';
import { getStaticUrl } from '@/utils/url';
const router = useRouter();
const commentStore = useCommentStore();
const articleStore = useArticleStore();

// 分页和筛选状态
const current = ref(1);
const pageSize = ref(10);
const filterStatus = ref(null);
const searchKeyword = ref('');

// 回复相关
const replyModalVisible = ref(false);
const replyContent = ref('');
const currentComment = ref(null);
const submitting = ref(false);

// 文章缓存
const articleCache = ref({});

// 表格列定义
const columns = [
  {
    title: '评论内容',
    dataIndex: 'content',
    key: 'content',
    ellipsis: true,
    width: '30%'
  },
  {
    title: '文章',
    key: 'article',
    dataIndex: 'articleId',
    width: '15%'
  },
  {
    title: '评论者',
    key: 'user',
    dataIndex: 'userId',
    width: '15%'
  },
  {
    title: '评论时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: '15%',
    sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime)
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: '10%',
    filters: [
      { text: '已发布', value: 1 },
      { text: '待审核', value: 0 },
      { text: '已拒绝', value: -1 }
    ],
    onFilter: (value, record) => record.status === value
  },
  {
    title: '操作',
    key: 'action',
    width: '15%'
  }
];

onMounted(() => {
  fetchComments();
  fetchArticles();
});

// 获取评论列表
const fetchComments = async () => {
  await commentStore.getCommentList(current.value, pageSize.value, filterStatus.value);
};

// 获取文章列表（用于显示文章标题）
const fetchArticles = async () => {
  try {
    const res = await articleStore.getArticleList(1, 100);
    res.records.forEach(article => {
      articleCache.value[article.id] = article.title;
    });
  } catch (error) {
    console.error('获取文章列表失败:', error);
  }
};

// 获取文章标题
const getArticleTitle = (articleId) => {
  return articleCache.value[articleId] || `文章ID: ${articleId}`;
};

// 查看文章
const viewArticle = (articleId) => {
  router.push(`/article/preview/${articleId}`);
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

// 格式化评论内容（处理表情、链接等）
const formatContent = (content) => {
  if (!content) return '';
  // 这里可以添加更复杂的格式化逻辑，如解析表情、链接等
  return content;
};

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 1: return 'green';
    case 0: return 'orange';
    case -1: return 'red';
    default: return 'default';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1: return '已发布';
    case 0: return '待审核';
    case -1: return '已拒绝';
    default: return '未知';
  }
};

// 处理页码变化
const handlePageChange = (page) => {
  current.value = page;
  fetchComments();
};

// 处理每页条数变化
const handleSizeChange = (current, size) => {
  pageSize.value = size;
  fetchComments();
};

// 处理筛选状态变化
const handleFilterChange = () => {
  current.value = 1;
  fetchComments();
};

// 处理搜索
const handleSearch = () => {
  current.value = 1;
  fetchComments();
};

// 审核通过评论
const handleApprove = async (record) => {
  try {
    await commentStore.reviewComment(record.id, 1);
    message.success('评论已通过审核');
    fetchComments();
  } catch (error) {
    message.error('操作失败');
  }
};

// 拒绝评论
const handleReject = async (record) => {
  try {
    await commentStore.reviewComment(record.id, -1);
    message.success('评论已被拒绝');
    fetchComments();
  } catch (error) {
    message.error('操作失败');
  }
};

// 删除评论
const handleDelete = async (record) => {
  try {
    await commentStore.deleteComment(record.id);
    message.success('评论已删除');
    fetchComments();
  } catch (error) {
    message.error('删除失败');
  }
};

// 回复评论
const handleReply = (record) => {
  currentComment.value = record;
  replyContent.value = '';
  replyModalVisible.value = true;
};

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    message.warning('请输入回复内容');
    return;
  }
  
  submitting.value = true;
  try {
    await commentStore.replyComment({
      articleId: currentComment.value.articleId,
      content: replyContent.value,
      parentId: currentComment.value.id,
      replyToUserId: currentComment.value.userId
    });
    
    message.success('回复成功');
    replyModalVisible.value = false;
    fetchComments();
  } catch (error) {
    message.error('回复失败');
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.comment-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-actions {
  display: flex;
  align-items: center;
}

.comment-content {
  max-width: 400px;
}

.reply-info {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.user-info {
  display: flex;
  align-items: center;
}

.username {
  margin-left: 8px;
}

.original-comment {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 16px;
}
</style> 